import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { get } from '@/utils/index'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'layout',
    redirect: '/message',
    meta: {},
    component: () => import('../components/layout.vue'),
    children: [
      {
        path: '/message',
        name: 'message',
        redirect: '',
        meta: { title: '消息', keepAlive: true },
        component: () => import('@/view/message/index.vue'),
      },
      {
        path: '/contact',
        name: 'contact',
        redirect: '',
        meta: { title: '联系人', keepAlive: true },
        component: () => import('@/view/contact/index.vue'),
      },
      {
        path: '/my',
        name: 'my',
        redirect: '',
        meta: { title: '我的', keepAlive: true },
        component: () => import('@/view/my/index.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    redirect: '',
    meta: {},
    component: () => import('../view/login/index.vue'),
  },
  {
    path: '/contactInfo',
    name: 'contactInfo',
    redirect: '',
    meta: { title: '联系人详情', keepAlive: false },
    component: () => import('@/view/contactInfo/index.vue'),
  },
  {
    path: '/im',
    name: 'im',
    redirect: '',
    meta: { title: '视频聊天页面', keepAlive: true },
    component: () => import('@/view/im/index.vue'),
  },
  {
    path: '/videoChat',
    name: 'videoChat',
    redirect: '',
    meta: { title: '视频聊天页面', keepAlive: true },
    component: () => import('@/view/videoChat/index.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const hasToken = get('token')
  if (hasToken) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
